"""
数据处理层
"""

import os, pickle
from conf import settings


# 从文件中读对象数据函数
def select_data(cls, name):
    # 1. 构造要读的文件路径
    class_name = cls.__name__

    DIR_PATH = os.path.join(
        settings.DB_PATH, class_name
    )

    # 2. 如果文件不存在则返回None
    if not os.path.exists(DIR_PATH):
        return None

    OBJ_PATH = os.path.join(
        DIR_PATH, name
    )

    if not os.path.exists(OBJ_PATH):
        return None

    # 3. 如果文件存在则读出并返回对象
    with open(OBJ_PATH, mode='rb') as f:
        obj = pickle.load(f)
        return obj


# 写对象数据到文件中函数
def save_data(obj):
    # 1. 构造要写的文件路径
    class_name = obj.__class__.__name__

    DIR_PATH = os.path.join(
        settings.DB_PATH, class_name
    )

    # 2. 如果文件目录不存在则创建
    if not os.path.exists(DIR_PATH):
        os.mkdir(DIR_PATH)
    
    OBJ_PATH = os.path.join(
        DIR_PATH, obj.name
    )

    # 3. 将对象数据写入到文件目录下的文件路径
    with open(OBJ_PATH, mode='wb') as f:
        pickle.dump(obj, f)
